﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Ajax.Models;
using Ajax.Models.Domain;

namespace Ajax.Controllers
{
    public class NewsController : Controller
    {
        public ActionResult Index(int page, int size)
        {
            var viewModel = new NewsViewModel();

            var context = new AjaxContext();

            var skip = (page - 1) * size;
            if (skip < 0) skip = 0;
            viewModel.News = context.News.OrderBy(x=>x.Id).Skip(skip).Take(size).ToList();

            return View(viewModel);
        }

        public ActionResult Detail(int newId)
        {
            var viewModel = new NewsDetailViewModel();
            var context = new AjaxContext();
            viewModel.News = context.News.FirstOrDefault(x => x.Id == newId);
            viewModel.NewsComments = new CommentViewModel
                                         {
                                             Comments = context.Comments.Where(x => x.NewId == newId).ToList(),
                                             NewComment = new Comment {NewId = newId}
                                         };
            return View(viewModel);
        }

        public ActionResult AddComment(CommentViewModel viewModel)
        {
            var context = new AjaxContext();
            if (ModelState.IsValid)
            {
                
                context.Comments.Add(viewModel.NewComment);
                context.SaveChanges();

                viewModel.NewComment = new Comment() { NewId = viewModel.NewComment.NewId };
            }
            viewModel.Comments = context.Comments.Where(x => x.NewId == viewModel.NewComment.NewId).ToList();
            Thread.Sleep(1000);
            return PartialView("Comments", viewModel);
        }

        [HttpGet]
        public ActionResult Add()
        {
            var viewModel = new NewsAddViewModel {New = new New()};
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Add(NewsAddViewModel viewModel)
        {
            var context = new AjaxContext();
            context.News.Add(viewModel.New);
            context.SaveChanges();
            return Redirect("/News/1/5/Index");
        }

    }
}
